package com.base.data.elasticsearch.core.syncmapping;

import com.google.gson.JsonObject;
import com.base.data.elasticsearch.core.mapping.BaseElasticsearchPersistentEntity;
import com.base.data.elasticsearch.core.operation.BaseElasticsearchOperations;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 */
public class BaseElasticMappingHandler {
    private static final Logger logger = LoggerFactory.getLogger(BaseElasticMappingHandler.class);

    /**
     *  初始化 类 es index-type 数据
     * @param claz
     * @param elasticsearchOperations
     * @param <T>
     */
    public static <T> void initClazzStructure(Class<T> claz, BaseElasticsearchOperations elasticsearchOperations) {
        final BaseElasticsearchPersistentEntity persistentEntityFor = elasticsearchOperations.getPersistentEntityFor(claz);
        createIndexAndCreateMappingByRestClient(persistentEntityFor.getIndexName(), persistentEntityFor.getIndexType(), claz,elasticsearchOperations);
    }


    /**
     * create index put  add type post
     * 根据信息自动创建索引与mapping
     * 构建mapping描述    有问题
     *
     * @return
     */
    private static <T> void createIndexAndCreateMappingByRestClient(String index, String type, Class<T> claz, BaseElasticsearchOperations elasticsearchOperations) {
        elasticsearchOperations.createIndex(claz);
        JsonObject existPropJson = elasticsearchOperations.typeExists(index,type);
        if(null == existPropJson){
            //创建type mapping
            elasticsearchOperations.putMapping(claz);
        }else {
            //更新type mapping
            elasticsearchOperations.updateTypeMapping(index,type,claz,existPropJson);
        }
    }


}